package com.diudiu.diudiu.service.impl;


import cn.hutool.core.date.LocalDateTimeUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baidu.aip.face.AipFace;
import com.diudiu.diudiu.entity.User;
import com.diudiu.diudiu.entity.UserFaceAi;
import com.diudiu.diudiu.mapper.UserFaceAiMapper;
import com.diudiu.diudiu.mapper.UserMapper;
import com.diudiu.diudiu.service.FaceAiService;
import com.diudiu.diudiu.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.HashMap;

@Service
public class FaceAiServiceImpl implements FaceAiService {

    public static final String APP_ID = "59922120";
    public static final String API_KEY = "xr5Txd7BskFi6kbN8Rh4DKEs";
    public static final String SECRET_KEY = "bIh23M9yDZ1fcrhRWJtnKS3WdNXjjmfq";


    @Resource
    private UserMapper userMapper;

    @Autowired
    UserFaceAiMapper userFaceAiMapper;

    @Override
    public void addUser(String image,  String userId) {

    }

    @Override
    public void faceDelete(String userId, String faceToken) {

    }

    @Override
    public Object search(String image,Integer userId,int state) {

        AipFace client = new AipFace(APP_ID, API_KEY, SECRET_KEY);
        HashMap<String, Object> options = new HashMap<String, Object>();
        options.put("match_threshold", "60");
        options.put("max_user_num", "1");
        JSONObject res = JSON.parseObject(client.search(image, "BASE64", groupId,options).toString());

         System.err.println(res.toString());

        if(res.getString("error_code").equals("0")){
            JSONObject resJson = res.getJSONObject("result");
            JSONArray resArray = resJson.getJSONArray("user_list");
            if(resArray != null && resArray.size() > 0){
                Integer userId1 =resArray.getJSONObject(0).getInteger("user_id");
                User user =  userMapper.selectById(userId1);
                UserFaceAi userFaceAi = new UserFaceAi();
                userFaceAi.setUserName(user.getName());
                userFaceAi.setUserId(userId1);
                userFaceAi.setState(state);
                userFaceAi.setImage("data:image/jpeg;base64,"+image);
                DateTimeFormatter dtf2 = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");

                String strDate2 = dtf2.format(LocalDateTime.now());
                userFaceAi.setCreateTime(strDate2);
                userFaceAiMapper.insert(userFaceAi);
            }
        }
        return JSON.parse(res.toString());
    }
}
